<!--
 * @Author: csh
 * @Date: 2022-09-19
 * @LastEditors: csh
 * @LastEditTime: 2022-11-02
 * @Description: file content
 * @FilePath: /webrtc-demo/DownloadRecorder.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <link rel="icon" type="image/svg+xml" href="/vite.svg" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>WebRTC Demos - Recorder and Download</title>
  <script src="https://cdn.temasys.io/adapterjs/0.15.x/adapter.debug.js"></script>
  <script src="public/EBML.js"></script>
</head>

<body>
  <div>
    <br />
    <button onclick="showCamera()">ShowCamera</button>
    <button onclick="startRecord()">StartRecord</button>
    <br />
    <br />
    <video id="videoElm" controls autoplay></video>
  </div>
  <script>

    async function getSeekableBlob(originBlob) {
      const Decoder = new EBML.Decoder();
      const buf = await originBlob.arrayBuffer()
      console.log('buf', buf);
      const ebmlElms = Decoder.decode(buf);
      console.log(ebmlElms);

      const reader = new EBML.Reader();
      ebmlElms.forEach(element => {
        reader.read(element)
      });
      reader.stop();
      console.log('reader', reader)

      const refinedMetadataBuf = EBML.tools.makeMetadataSeekable(
        reader.metadatas,
        reader.duration,
        reader.cues
      )
      console.log('refinedMetadataBuf', refinedMetadataBuf)
      const body = buf.slice(reader.metadataSize)
      const aimBlob = new Blob([refinedMetadataBuf, body], {
        type: 'video/webm'
      })
      console.log('aimBlob', aimBlob)
      return aimBlob
    }

    // 获取摄像头，并显示到 video 标签中
    function showCamera() {
      navigator.mediaDevices.getUserMedia({ audio: false, video: true })
        .then(function (stream) {
          document.getElementById('videoElm').srcObject = stream;
        })
    }

    // 开始录制
    function startRecord() {
      const stream = document.getElementById('videoElm').srcObject;
      if (!stream) {
        console.error('startRecord stream is null');
        return;
      }
      // please use h264 to enable hardware encode accelerate and decrease cpu usage
      const mimeType = 'video/webm\;codecs=vp8';
      let blobSlice = [];

      const mediaRecorder = new MediaRecorder(stream, {
        mimeType,
        videoBitsPerSecond: 1e6
      });

      mediaRecorder.ondataavailable = (event) => {
        blobSlice.push(event.data);
      }

      mediaRecorder.onstop = async () => {
        console.log('onstop')
        const newBlob = new Blob([...blobSlice], { type: mimeType });
        const aimBlob = await getSeekableBlob(newBlob);

        var videoURL = URL.createObjectURL(aimBlob);
        console.log('videoURL', videoURL);
        var a = document.createElement("a");    //模拟链接，进行点击下载
        a.href = videoURL;
        a.style.display = "none";    //不显示
        a.download = "video.mp4";
        a.click();

        blobSlice = [];
      };

      // using timeslice to avoid memory consumption in renderer process, and generate a blob object each second
      mediaRecorder.start(1000);
      setTimeout(() => mediaRecorder.stop(), 61000);
    }

  </script>
</body>

</html>